package com.lcy.app.common.util;

import android.app.Activity;
import android.app.DownloadManager;
import android.content.Context;
import android.net.Uri;
import android.os.Environment;

import androidx.appcompat.app.AppCompatActivity;

import com.lcy.app.activity.MainActivity;
import com.lcy.app.api.MusicApi;
import com.lcy.app.api.domain.RespEntity;
import com.lcy.app.api.http.HTTP;

public class DownloadHelper {

    public static void downloadFile(Context context, String fileUrl, String fileName) {
        DownloadManager downloadManager = (DownloadManager) context.getSystemService(Context.DOWNLOAD_SERVICE);
        Uri uri = Uri.parse(fileUrl);

        DownloadManager.Request request = new DownloadManager.Request(uri);
        request.setDestinationInExternalPublicDir(Environment.DIRECTORY_DOWNLOADS, fileName);
        request.setNotificationVisibility(DownloadManager.Request.VISIBILITY_VISIBLE_NOTIFY_COMPLETED);

        if (downloadManager != null) {
            downloadManager.enqueue(request);
        }
    }

    private static String getDownloadLink(AppCompatActivity context, String fileId) {
        HTTP<String> linkHttp = new HTTP<>();
        RespEntity<String> musicResEntity = linkHttp
                .synRequest(context, retrofit ->
                        retrofit.create(MusicApi.class).getLink(MainActivity.token, fileId));

        if (HttpUtil.isOk(musicResEntity)) {
            return musicResEntity.getData();
        }
        throw new RuntimeException("获取链接失败");
    }

    public static String getMusicLink(AppCompatActivity context, String fileId) {
        String linkId = getDownloadLink(context,fileId);
        return HTTP.BASE_URL + "file/link/" + linkId;
    }
}